package com.xxx.mybaitis;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Collection;

/**
 * jdk动态代理实现mapper接口
 */
public class MappedProxy implements InvocationHandler {
	
	private SqlSession sqlSession;
	
	public MappedProxy(SqlSession sqlSession) {
		this.sqlSession = sqlSession;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		String methodName = method.getName();
		String statement = method.getDeclaringClass().getName() + "." + methodName;
		
		MappedStatement mappedStatement = sqlSession.getConfiguration().getMappedStatementMap().get(statement);
		
		if("select".equals(mappedStatement.getSqlCommandType())) {
			Class<?> clazz = method.getReturnType(); // 返回结果类型
			// 判断返回结果类型：如果是Collection类型，则执行selectList；如果不是，则执行selectOne
			if(Collection.class.isAssignableFrom(clazz)) { // 集合类型
				return sqlSession.selectList(statement, args);
			} else { // 非集合类型
				return sqlSession.selectOne(statement, args);
			}
		} else {
			return sqlSession.update(statement, args);
		}
	}

}
